<template>

    <div class="flex">
        <div class="register">
            <div class="title">Aspiration inn 1.3.2</div>
            <div class="form">
                <n-form ref="formRef" :label-width="80" :model="formValue" :rules="rules" :size="size">
                    <n-form-item v-if="isRegisterShow" path="email">
                        <n-input size="large" v-model:value="formValue.email" placeholder="邮箱号" />
                    </n-form-item>
                    <n-form-item path="username">
                        <n-input size="large" maxlength="10" v-model:value="formValue.username" placeholder="名称" />
                    </n-form-item>
                    <n-form-item path="password">
                        <n-input size="large" show-password-on="click" :type="streanType" maxlength="16"
                            v-model:value="formValue.password" placeholder="密码" />
                    </n-form-item>
                    <n-form-item path="code">
                        <n-input @keyup.enter="handlerCheck" :allow-input="onlyAllowNumber" maxlength="6"
                            v-model:value="formValue.code" :placeholder="codeResult.start + '+' + codeResult.end" />

                    </n-form-item>
                    <n-form-item>
                        <n-button size="large" class="mt-20" type="primary" style="width: 100%;" attr-type="button"
                            @click="handlerCheck">
                            {{ isRegisterShow ? '注册' : '登录' }}
                        </n-button>
                    </n-form-item>
                </n-form>
            </div>

            <div class="footer">
                <n-flex>
                    <n-button type="primary" text tag="a" target="_blank" @click="handerRegister">注册</n-button>
                    <n-button type="info" text>更多</n-button>
                </n-flex>
            </div>

            <n-spin :show="show">
                <div class="random mt-20">
                    <n-scrollbar x-scrollable>
                        <n-flex justify="space-between">
                            <n-tag v-for="(item) in resultWeiboData" :key="item.id" :bordered="false" :type="item.type">
                                {{ item.title }}
                            </n-tag>
                        </n-flex>
                    </n-scrollbar>
                </div>
            </n-spin>

        </div>
        <div class="Masking"></div>
    </div>
</template>

<script setup lang="ts">
// @ts-ignore
import { FormInst, useMessage, FormItemRule } from 'naive-ui'
import { usrRegister, usrLogin, obtainWeibo } from '@/apis/index';
import { useMain } from '@/store/index';

const store = useMain();
const formRef = ref<FormInst | null>(null);
const message = useMessage();
const router = useRouter();
const size = ref<'small' | 'medium' | 'large'>('medium')
const isRegisterShow = ref(false);
const show = ref(true);
const streanType: any = ref('password');
const resultWeiboData: any = ref({});
const color = ['success', 'warning', 'error', 'info', 'default'];
const currentColor: any = ref([]);
function randCode(startNum: number, endNum: number): number {
    return Math.floor(Math.random() * (endNum - startNum + 1) + startNum);
}


let codeResult = ref({ start: randCode(1, 10), end: randCode(1, 10) });
const formValue: any = ref({
    username: '',
    password: '',
    code: '',
    email: '',

})

const rules = {
    username: {
        required: true,
        message: '名称',
        trigger: 'blur'
    },
    email: {
        required: true,
        trigger: 'input',
        //@ts-ignore
        validator: (rule: FormItemRule, value: string) => {
            console.info(value)
            return new Promise<void>((resolve, reject) => {
                const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
                if (!reg.test(value)) {
                    reject(Error('非正确邮箱')) // reject with error message
                } else {
                    resolve()
                }
            })
        }
    },
    password: {
        required: true,
        message: '密码',
        trigger: ['input', 'blur']
    },
    code: {
        required: true,
        trigger: ['input', 'blur'],
        //@ts-ignore
        validator: (rule: FormItemRule, value: number) => {
            return new Promise<void>((resolve, reject) => {
                if (value != codeResult.value.start + codeResult.value.end) {
                    reject(Error('验证码错误')) // reject with error message
                }
                resolve()
            })
        }
    }
}

function handerRegister() {
    isRegisterShow.value = !isRegisterShow.value;
    if (isRegisterShow.value) {
        streanType.value = 'text';
        return;
    }
    streanType.value = 'password';
}



const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value);

async function handlerCheck(e: any) {
    e.preventDefault()
    formRef.value?.validate(async (errors) => {
        if (!errors) {
            if (!isRegisterShow.value) {
                const { data, status, message: msg } = await usrLogin(formValue.value);
                if (status === 200) {
                    store.setIsShwoMenu(true);
                    store.insterToken(data.token as string);
                    localStorage.setItem('t', data.token as string);
                    localStorage.setItem('l', data.level + '');
                    localStorage.setItem('day', data.createTime);
                    localStorage.setItem('countLevel', data.countLevel + '');
                    localStorage.setItem('avatar', data.avatar as string);
                    localStorage.setItem('u', data.username);
                    localStorage.setItem('designation', data.alias);
                    message.success(msg);
                    router.push('/');
                    return;
                } else {

                    message.error(msg);
                }
                return;
            }
            // 注册
            const { status, message: msg } = await usrRegister(formValue.value);
            if (status === 200) {
                message.success(msg + '去登录');
                isRegisterShow.value = false;
                // router.push('/registerAndLogin');
                return;
            }
            message.success(msg);
        } else {
            codeResult.value = { start: randCode(1, 10), end: randCode(1, 10) }
            message.error('信息有误')
        }
    }).catch(err => {
        console.info(err)
    })
}
onMounted(() => {
    obtainWeibo().then(res => {
        if (res.data.code === 200) {
            let data = res.data.data.list;
            for (let i = 0; i < res.data.data.list.length / 5; i++) {
                for (let index = 0; index < color.length; index++) {
                    currentColor.value.push(color[index]);
                }
            }
            resultWeiboData.value = data.map((item: any, i: number) => {
                return {
                    id: item.heat,
                    title: item.title,
                    link: item.link,
                    type: currentColor.value[i]
                }
            });
            show.value = false;
        }
    })
})
</script>

<style lang="scss" scoped>
.n-form-item {
    grid-template-rows: none !important;
}

.flex {
    display: flex;
    justify-content: center;
}

.Masking {
    width: 100%;
    height: 100%;
    background-color: #eeeef8;
    opacity: 0.4;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
    height: 100%;
}

.random {
    height: 260px;
    overflow: auto;
}

.register {
    width: 80%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 8px;
    position: relative;
    top: 180px;
    z-index: 999999;

    .n-input {
        border-radius: 5px;
    }

    :deep(.n-input__eye) {
        position: absolute;
        right: 10px;
    }

    :deep(.n-input__border) {
        border: none !important;

    }

    :deep(.n-input__state-border) {
        border: none !important;
        // box-shadow:none !important;
        outline: 0;
    }

    .title {
        position: fixed;
        top: 30px;
        padding: 20px 20px;
        font-size: 18px;
        font-weight: 500;
        color: #252933;
        // border-bottom: 1px solid rgba(228, 230, 235, 0.5);
    }

    .info-title {
        font-size: 16px;
        font-weight: 500;
        margin: 0 0 1.33rem;
        color: #252933;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
    }

    .form {
        width: 280px;
        text-align: center;

    }

}
</style>